package service;

import dao.TransferDao;
import protectjava.jdbc.DataSourceUtils;
import utils.MyDataSourceUtils;

import java.sql.Connection;
import java.sql.SQLException;

public class TransferService {

    public int transfer(int out, int in , double money){
//        调用dao层
        TransferDao dao = new TransferDao();
        int isTransferSuccess = 1;
        Connection conn = null;
        try {
////            获得连接
//            conn = DataSourceUtils.getConnection();
////            开启事物
//            conn.setAutoCommit(false);
////            判断余额是否足够

//            开启事务
            MyDataSourceUtils.starTransaction();

//            使用ThreadLocal存储connection
            Connection currentConnection = MyDataSourceUtils.getCurrentConnection();


            boolean is = dao.balance(conn,money,out);
            if (is = true){
//            调用转出方法
            dao.out(out, money);
//            调用转入方法
            dao.in(in, money);
            }else {
                isTransferSuccess = 3;
            }
        } catch (Exception e) {
            e.printStackTrace();
//            回滚事务
            MyDataSourceUtils.rollback();
            isTransferSuccess = 2;
        }finally {
//            提交事物
            try {
                MyDataSourceUtils.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            return isTransferSuccess;

        }


    }
}
